<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>图像识别管理系统</title>
    <link href="../css/common.css" rel="stylesheet">
    <link rel="stylesheet" href="../css/layui.css" media="all">
    <link id="layuicss-layer" rel="stylesheet" href="../css/modules/layer/default/layer.css" media="all">
    <script src="../js/jquery-1.12.4.js"></script>
    <script type="text/javascript" src="../js/jstime/laydate.js"></script>
    <script type="text/javascript" src="../js/layui.js" charset="utf-8"></script>
    <script type="text/javascript" src="../js/common.js" charset="utf-8"></script>
    <style>
        #wrapper {
            position: relative;
            display: flex;
        }

        #left,
        #right {
            width: 50%;
            height: 90vh;
        }

        #line {
            position: absolute;
            left: calc(50% - 3px);
            width: 6px;
            height: calc(100% - 20px);
            margin: 10px 0;
            cursor: col-resize;
            background-color: #e2e2e2;
        }

        .searchBar input.laydate-icon {
            width: 100px;
        }

        /*#tableTwoTatol {*/
        /*    height: 40px;*/
        /*    line-height: 40px;*/
        /*    font-size: 12px;*/
        /*    padding-left: 16px;*/
        /*    margin-top: -10px;*/
        /*    !*border: 1px solid #e6e6e6;*!*/
        /*    border-top: none;*/
        /*}*/
    </style>
</head>

<body>
<div class="searchBar">
    <label>识别名称：</label><input id="title" />
    <label>创建人：</label><input id="username" readonly/>
    <input hidden id="createBy" />
    <button id="search" data-type="check">查询</button>
</div>

<div id="wrapper">
    <!-- 左侧 -->
    <div id="left">
        <script type="text/html" id="toolbar">
            <button class="layui-btn layui-btn-sm" lay-event="refresh1">刷新</button>
            <button class="layui-btn layui-btn-sm" lay-event="add1">新增</button>
            <button class="layui-btn layui-btn-sm" lay-event="modify1">修改</button>
            <button class="layui-btn layui-btn-sm" lay-event="remove1">删除</button>
        </script>
        <div style="margin: 0 5px 0 10px;">
            <table id="tableOne" lay-filter="tableOne"></table>
        </div>
    </div>
    <!-- 右侧 -->
    <div id="right">
        <script type="text/html" id="toolbar2">
            <button class="layui-btn layui-btn-sm" lay-event="refresh2">刷新</button>
            <button class="layui-btn layui-btn-sm" lay-event="add2">新增</button>
            <button class="layui-btn layui-btn-sm" lay-event="modify2">修改</button>
            <button class="layui-btn layui-btn-sm" lay-event="remove2">删除</button>
        </script>
        <div style="margin: 0 10px 0 5px;">
            <table id="tableTwo" lay-filter="tableTwo"></table>
            <div id="tableTwoTatol"></div>
        </div>
    </div>
    <!-- 分隔条 -->
    <div id="line"></div>
</div>

</body>

</html>

<script type="text/javascript">
    layui.config({base:'../js/lay/modules/'}).extend({tableSelect:'tableSelect'}).use(["table", "layer", "upload", "element",'tableSelect'], function () {
        let table = layui.table,element = layui.element,form = layui.form,upload = layui.upload,tableSelect = layui.tableSelect,tree = layui.tree,treeSelect = layui.treeSelect;

        var yesIndex = "";
        var sysLevel = "";
        var sH = layui.$(".searchBar").height();
        sH += 45;
        // sH = 'full-' + sH;

        var elemClass;

        var tableTwoCol = [
            { type: 'checkbox', fixed: 'left' },
            { field: 'id',  title: '唯一编号', sort: true ,width:'10%'}
            , { field: 'name',  sort: true, title: '名称',width:'50%' }
            , { field: 'score',  sort: true, title: '相似度',width:'50%' }
            , { field: 'message',  sort: true, title: '内容',width:'50%' }
            , { field: 'imagePath',  sort: true, title: '图片路径',width:'50%' }
            , { field: 'createdBy',  sort: true, title: '创建人ID',width:'20%' }
            , { field: 'createdTime',  title: '创建时间', sort: true,width:'10%' }
        ]

        // 初始化表格1
        function initTableOne() {
            table.render({
                elem: '#tableOne'
                , toolbar: '#toolbar' // 开启头部工具栏，并为其绑定左侧模板
                , defaultToolbar: ['filter', 'print']
                , contentType: "application/json;charset=UTF-8"
                , height: 'full-100'
                , method: "post"
                , request: {
                    pageName: "page", // 页码的参数名称，默认：page
                    limitName: "rows" // 每页数据量的参数名，默认：limit
                }
                , limit: 50
                , limits: [50, 100, 500, 1000, 2000]
                /* 		,headers: { token: localStorage.getItem("token") }	 */
                , parseData: function (res) {//将回调函数解析成table所规定的数据格式
                    return {
                        msg: res.errMsg,
                        count: res.data ? res.data.total : 0,
                        data: res.data ? res.data.rows : [],
                        code: res.errCode
                    };
                }
                , url: webUrl + '/identificationContent/findPage' //数据接口
                , cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'id',  title: '唯一编号', sort: true ,width:'10%'}
                    , { field: 'name',  sort: true, title: '识别名称',width:'20%' }
                    , { field: 'imagePath',  sort: true, title: '图片路径',width:'30%' }
                    , { field: 'username',  sort: true, title: '创建人账号',width:'20%' ,templet: function (d) { return d.userRespVo.username;}}
                    , { field: 'nickname',  title: '创建人昵称', sort: true,width:'20%' ,templet: function (d) { return d.userRespVo.nickname;}}
                ]]
                , page: true
                , where: {
                    token: getCookie("token")
                },
                done: function (res) {
                    if (res.code == "000001") {
                        layer.confirm('登录信息已过期，请重新登录', {title: '系统提示', btn: ['确认']}, function (index) {
                            layer.close(index);
                            window.parent.returnLogin();
                        });
                    }

                    // 默认选中第一条 || 保存了当前正在查看的那条数据，存在就显示
                    if (res.data.length) {
                        id = res.data[0]['id'];
                        initTableTwo(id);
                        var tr = $(".layui-table").find("tbody tr[data-index='0']");
                        tr.addClass("layui-table-click").siblings().removeClass("layui-table-click");
                    }else {
                        id = "";
                        initTableTwo(id);
                    }
                }
            })
            refreshTable(1, 'tableOne')
        }

        var num = 0;//全局变量,防止重复点击
        var id = "";
        //监听行单击事件（双击事件为：rowDouble）
        table.on('row(tableOne)', function(obj) { //lay-filter="test"
            var selector = obj.tr.selector;//获取选中的data-index
            if (num != selector) {
                obj.tr.addClass("layui-table-click").siblings().removeClass("layui-table-click");
                num = selector;//必须放在前面,后续点击依然会触发该方法
                id = obj.data.id;
                console.log(id);
                initTableTwo(obj.data.id);
            }

        });


        // 初始化表格2
        function initTableTwo(id) {
            console.log(id);
            table.render({
                elem: '#tableTwo'
                , toolbar: '#toolbar2' //开启头部工具栏，并为其绑定左侧模板
                , defaultToolbar: ['filter', 'print']
                , height: 'full-100'
                , method: "post"
                // , page: false
                // , limit: Number.MAX_VALUE
                , contentType: "application/json;charset=UTF-8"
                // , request: {
                //     pageName: "page", // 页码的参数名称，默认：page
                //     limitName: "rows" // 每页数据量的参数名，默认：limit
                // }
                , limit: 50
                , limits: [50, 100, 500, 1000, 2000]
                /* 		,headers: { token: localStorage.getItem("token") }	 */
                , parseData: function (res) {//将回调函数解析成table所规定的数据格式
                    return {
                        msg: res.errMsg,
                        count: res.data ? res.data.length : 0,
                        data: res.data ? res.data : [],
                        code: res.errCode
                    };
                }
                , url: webUrl + '/identificationContent/findListByParentId' //数据接口
                , cols: [tableTwoCol]
                // , page: true
                , where: {
                    "parentId":id
                },
                done: function (res) {
                    if (res.code == "000001") {
                        layer.confirm('登录信息已过期，请重新登录', { title: '系统提示', btn: ['确认'] }, function (index) {
                            layer.close(index);
                            window.parent.returnLogin();
                        });
                    }
                    // $("#tableTwoTatol").text("共 " + res.data.length + " 条")
                }
            })
        }
        initTableOne();
        // 表格1头部工具栏事件
        table.on('toolbar(tableOne)', function (obj) {
            // var tableList1 = layui.table.cache["tableOne"];
            var checkStatus = table.checkStatus(obj.config.id);
            let len = checkStatus.data.length;
            switch (obj.event) {
                case 'refresh1':
                    elemClass = null;
                    refreshTable(1, 'tableOne')
                    break;
                case 'add1':
                    addFunction();
                    break;
                case 'modify1':

                    if (len < 1) {
                        layer.msg('请选择需要修改的单条数据');
                        return;
                    }
                    if (len > 1) {
                        layer.msg('只能修改单条数据');
                        return;
                    }
                    editFunction(checkStatus.data[0]);
                    break;
                case 'remove1':
                    if (len < 1) {
                        layer.msg('请选择需要删除的数据');
                        return;
                    }
                    deletedFunction(checkStatus.data);
                    break;
            }
        })

        function addFunction() {
            let submitPopupContent =
                '<input type="hidden" id="new_id"/>' +
                '<div class="popupCont">' +
                '</div>' +
                '<div class="popupCont">' +
                '<label  class="w60" style="width:150px">识别内容:</label><select readonly="readonly" id="type"  style="width:150px">' +
                '<option >请选择</option>' +
                '<option value="1">通用物品与场景识别</option>' +
                '<option value="2">动物识别</option>' +
                '<option value="3">植物识别</option>' +
                '<option value="4">Logo识别</option>' +
                '<option value="5">果蔬识别</option>' +
                '<option value="6">菜品识别</option>' +
                '<option value="7">红酒识别</option>' +
                '<option value="8">货币识别</option>' +
                '<option value="9">地标识别</option>' +
                '</select>' +
                '</div>' +
                '<div class="layui-upload" style="margin-left: 110px;margin-bottom: 30px;">' +
                '            <button type="button" class="layui-btn" id="uploadImg">上传图片</button>' +
                '            <div style="display:none;">' +
                '                <input type="text" name="img_url" id="ipt_fileName" autocomplete="off" class="layui-input">' +
                '            </div>' +
                '            <div class="layui-upload-list">' +
                '                <img class="layui-upload-img" style="width:100px;height:100px;" id="img_id">' +
                '                <p id="demoText"></p>' +
                '            </div>' +
                '            <div style="width: 95px;">' +
                '                <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="upload_filter">' +
                '                    <div class="layui-progress-bar" lay-percent=""></div>' +
                '                </div>' +
                '            </div>' +
                '        </div>' +
                '<div class="popupCont">' +
                '<input type="hidden" id="userId" />' +
                '</div>';

            layer.open({
                type: 1,
                title: "添加",
                area: "40%",
                shade: 0.5,
                btn: ["确认", "取消"],
                btnAlign: "c",
                moveType: 1,
                content: submitPopupContent,
                success: function () {
                    uploadImage();
                    imageUrl = null;
                }, yes: (index) => {
                    confirmInfoMsg();
                    yesIndex = index;
                }
            });

        }
        function confirmInfoMsg() {

            layer.close(yesIndex);
        }
        function editFunction(data) {
        let submitPopupContent =
            '<input type="hidden" id="newId"/>' +
            '<div class="layui-row popupCont">' +
            '<label  class="w60" style="width:200px;">识别名称:</label><input id="newName"   style="width:150px" />' +
            '</div>' +
            '<div class="layui-row popupCont">' +
            '<label  class="w60" style="width:200px;">图片路径:</label><input id="newPath"   style="width:300px"/>' +
            '</div>';

        layer.open({
            type: 1,
            title: "修改",
            area: "80%",
            shade: 0.5,
            btn: ["确认", "取消"],
            btnAlign: "c",
            moveType: 1,
            content: submitPopupContent,
            success: function () {
                if (data && data.id) {
                    $("#newId").val(data.id);
                    $("#newName").val(data.name);
                    $("#newPath").val(data.imagePath);
                }


            },
            yes: (index) => {
                let newId = $("#newId").val();
                let newName = $("#newName").val();
                let newPath = $("#newPath").val();
                newName.trim();
                newPath.trim();
                if (newPath === "") {
                    layer.msg('图片路径不能为空');
                    return;
                }
                var submitData = {
                    "id":newId,
                    "name":newName,
                    "imagePath": newPath,
                }
                var url = webUrl + '/identificationContent/modify';
                yesIndex = index;
                sendPostAjax(
                    url,
                    submitData,
                    (res) => {
                        if (res.errCode === "000000") {
                            layer.msg("成功");
                        }
                        else if(res.errCode === "000001") {
                            layer.msg("未授权，请重新登录");
                            window.parent.returnLogin();
                        }
                        else {
                            layer.msg("失败");
                        }
                        layer.close(yesIndex);
                        search(1);
                    }
                )
            }
        });

    }
        function deletedFunction(data) {
            var idList = '';
            for (var i = 0; i < data.length; i++) {
                if (i == data.length - 1) {
                    idList += data[i].id;
                } else {
                    idList += data[i].id + ",";
                }
            }
            sendPost(
                webUrl + '/identificationContent/remove',
                idList,
                (res) => {
                    if (res.errCode === "000000") {
                        layer.msg("成功");
                    } else {
                        layer.msg("失败");
                    }
                    search(1);
                }
            )

        }


        // 表格2头部工具栏事件
        table.on('toolbar(tableTwo)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;
            let len = checkStatus.data.length;
            switch (obj.event) {
                case 'refresh2':
                    refreshTable(1, 'tableTwo')
                    break;
                case 'add2':
                    editFunction2();
                    break;
                case 'modify2':
                    if (len < 1) {
                        layer.msg('请选择需要修改的单条数据');
                        return;
                    }
                    if (len > 1) {
                        layer.msg('只能修改单条数据');
                        return;
                    }
                    editFunction2(data[0]);
                    break;
                case 'remove2':
                    if (len < 1) {
                        layer.msg('请选择需要删除的数据');
                        return;
                    }
                    deletedFunction2(checkStatus.data);
                    break;
            }
        })


        function editFunction2(data) {
            let submitPopupContent =
                '<input type="hidden" id="newId2"/>' +
                '<div class="layui-row popupCont">' +
                '<label  class="w60" style="width:200px;">名称:</label><input id="newName2"   style="width:150px" />' +
                '</div>' +
                '<div class="layui-row popupCont">' +
                '<label  class="w60" style="width:200px;">图片路径:</label><input id="newPath2"   style="width:300px"/>' +
                '</div>' +
                '<div class="layui-row popupCont">' +
                '<label  class="w60" style="width:200px;">相似度:</label><input id="newScore2"   style="width:300px"/>' +
                '</div>' +
                '<div class="layui-row popupCont">' +
                '<label  class="w60" style="width:200px;">内容:</label><textarea id="newMessage2"   style="width:300px"></textarea>' +
                '</div>';

            layer.open({
                type: 1,
                title: data && data.id ? "修改" : "添加",
                area: "80%",
                shade: 0.5,
                btn: ["确认", "取消"],
                btnAlign: "c",
                moveType: 1,
                content: submitPopupContent,
                success: function () {
                    if (data && data.id) {
                        $("#newId2").val(data.id);
                        $("#newName2").val(data.name);
                        $("#newPath2").val(data.imagePath);
                        $("#newScore2").val(data.score);
                        $("#newMessage2").val(data.message);
                    }


                },
                yes: (index) => {
                    let newId = $("#newId2").val();
                    let newName = $("#newName2").val();
                    let newPath = $("#newPath2").val();
                    let newScore = $("#newScore2").val();
                    let newMessage = $("#newMessage2").val();
                    let parentId = id;
                    newMessage.trim();
                    newScore.trim();
                    newName.trim();
                    newPath.trim();
                    if (newName === "") {
                        layer.msg('名称不能为空');
                        return;
                    }
                    if (newPath === "") {
                        layer.msg('图片路径不能为空');
                        return;
                    }
                    if (newScore === "") {
                        layer.msg('相似度不能为空');
                        return;
                    }
                    if (newMessage === "") {
                        layer.msg('内容不能为空');
                        return;
                    }
                    if (parentId === "") {
                        layer.msg('所属识别内容不能为空');
                        return;
                    }
                    var submitData = {
                        "parentId":parentId,
                        "score": newScore,
                        "message": newMessage,
                        "imagePath": newPath,
                        "name": newName,
                    }
                    var url = webUrl + '/identificationContent/saveInfo';
                    if (data && data.id) {
                        submitData.id = newId;
                        url = webUrl + '/identificationContent/modify';
                    }
                    yesIndex = index;
                    sendPostAjax(
                        url,
                        submitData,
                        (res) => {
                            if (res.errCode === "000000") {
                                layer.msg("成功");
                            }
                            else if(res.errCode === "000001") {
                                layer.msg("未授权，请重新登录");
                                window.parent.returnLogin();
                            }
                            else {
                                layer.msg("失败");
                            }
                            layer.close(yesIndex);
                            search(1);
                        }
                    )
                }
            });

        }


        function deletedFunction2(data) {
            var idList = '';
            for (var i = 0; i < data.length; i++) {
                if (i == data.length - 1) {
                    idList += data[i].id;
                } else {
                    idList += data[i].id + ",";
                }
            }
            sendPost(
                webUrl + '/identificationContent/remove',
                idList,
                (res) => {
                    if (res.errCode === "000000") {
                        layer.msg("成功");
                    } else {
                        layer.msg("失败");
                    }
                    search(1);
                }
            )

        }

        // 表格1/2刷新事件 ---- 执行重载
        function refreshTable(page, type) {
            switch (type) {
                case 'tableOne':
                    table.reload(type, {
                        page: {
                            curr: page
                        }
                        , where: {
                            deliverDateStartMin: $("#deliverDateStartMin").val(),
                            deliverDateStartMax: $("#deliverDateStartMax").val()
                        }
                    })
                    break;
                case 'tableTwo':
                    initTableTwo(id);
                    break;
            }
        }

        $('#search').on('click', function () {
            search(1);
        });

        //搜索
        function search(page) {
            //执行重载
            var query = page ? { page: { curr: page } } : {}
            console.log(layui.$("#createBy").val())
            query['where'] = {
                title: layui.$("#title").val(),
                message: layui.$("#message").val(),
                createdBy: layui.$("#createBy").val(),
            }
            table.reload('tableOne', query);

        }

        function resizeTableWidth() {
            var line = $("#line")
            var clientX, moveX, oldLeftWidth, oldRightWidth, oldlineLeft;
            // 鼠标按下
            line.on("mousedown", function (ev) {
                oldLeftWidth = parseInt($("#left").css("width"))
                oldRightWidth = parseInt($("#right").css("width"))
                oldlineLeft = parseInt($("#line").css("left"))
                var ev = ev || event;
                clientX = ev.clientX;
                var body = document.body;
                $("body").css("user-select", "none")

                body.addEventListener("mousemove", function (ev) {
                    var ev = ev || event;
                    moveX = ev.clientX;
                    if (clientX && oldLeftWidth + (moveX - clientX) > 356 && oldRightWidth - (moveX - clientX) > 320) {
                        line.css("left", oldLeftWidth + (moveX - clientX) - 3)
                        $("#left").css("width", oldLeftWidth + (moveX - clientX))
                        $("#right").css("width", oldRightWidth - (moveX - clientX))
                        table.resize('tableOne');
                        table.resize('tableTwo');
                    }
                })

                body.addEventListener("mouseup", function () {
                    clientX = null;
                    body.onmousemove = null;
                    body.onmouseup = null;
                    $("body").css("user-select", "auto")
                })
            })
        }
        resizeTableWidth()







//材料名称
        let url =  webUrl + '/userinfo/getPage';
        tableSelectHandle('#username', 'username', 'userId', url, '创建人', (elem, data) => { if (!data['data'] || data['data'].length < 1) return; elem.val(data['data'][0]['username']); $('#createBy').val(data['data'][0]['userId']); });




        function tableSelectInit(){
            //材料名称
            let url =  webUrl + '/identificationContent/findPage';
            tableSelectHandle('#identification', 'name', 'id', url, '识别内容名称', (elem, data) => { if (!data['data'] || data['data'].length < 1) return; elem.val(data['data'][0]['name']); $('#identificationId').val(data['data'][0]['id']); });

        }

        function tableSelectHandle(elem,field,checkId,url,title,doneCallBack){
            tableSelect.render({
                elem:elem,
                checkedKey:checkId, //表格唯一键，影响选中
                searchKey:field, //搜索输入框的name
                searchPlaceholder: title,
                table:{
                    url:url
                    ,method:'post'
                    , contentType: "application/json;charset=UTF-8"
                    ,page:true
                    ,limit:50
                    ,limits:[50,100,500,1000,2000]
                    ,where:{
                        token:getCookie('token')
                    }
                    ,request:{
                        pageName:'page'
                        ,limitName:'rows'
                    }
                    ,cols:[[
                        {type:'radio'},
                        {field:checkId,title:"唯一编号"},
                        {field:field,title:title},
                    ]]
                    ,parseData:function(res){
                        return {
                            code:res.errCode
                            ,msg:res.errMsg
                            ,data:res.data.rows
                            ,count:res.data.total
                        };
                    }
                },
                done:doneCallBack
            });
        }



        function uploadImage(){
            //常规使用 - 普通图片上传
            var uploadInst = upload.render({
                elem: '#uploadImg'
                , url: webUrl+'/identificationContent/identify'
                , before: function (obj) {
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#img_id').attr('src', result); //图片
                    });
                    element.progress('upload_filter', '0%'); //进度条
                    layer.msg('上传中', { icon: 16, time: 0 });
                    this.data = {
                        type:$("#type").val()
                    }
                }
                , done: function (res) {
                    if (res.errCode !== '000000') {
                        return layer.msg('上传失败');
                    }
                    $('#demoText').html(''); //置空上传失败的状态
                    $("#ipt_fileName").val(res.msg);
                    console.log(res)
                    imageUrl = res.data;

                }
                , error: function () {
                    //展示失败状态，并重新上传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #ff5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
                //进度条
                , progress: function (n, elem, e) {
                    element.progress('upload_filter', n + '%'); //可配合 layui 进度条元素使用
                    if (n == 100) {
                        layer.msg('上传完毕', { icon: 1 });
                    }
                }
            });
        }
    })

</script>